import React, {useMemo, useState} from "react";

export default function App() {
    const [inputValue, setInputValue] = useState("");
    const [startNum, setStartNum] = React.useState(0);
    const [, setResult] = React.useState(0);

    // useMemo相当于vue计算属性，作用: 用来缓存计算结果 如果deps为[] 则刷新页面只会执行1次，App函数重新渲染不会再次执行add函数
    // 如果deps为[startNum] 则每次startNum更新，App函数重新渲染会再次执行add函数，拿到最新的计算结果，startNum不更新则不会执行
    const add = useMemo(() => {
        console.log('开始计算===================');
        let res = startNum;
        for (let i = 0; i <= 100; i += 1) {
            res += i;
        }
        setResult(res);
        return res;
    }, [startNum])

    return <div>
        <div><span>结果值:</span>{add}</div>
        <span>开始值:</span><input onChange={e => setInputValue(e.target.value)} value={inputValue}/>
        <button onClick={() =>  inputValue && setStartNum(+inputValue)}>click</button>
    </div>
}